from .models import GoodsChannel


def get_categories():
    # 1.查询
    # 1.1分类
    channels = GoodsChannel.objects.all().order_by('group_id').order_by('sequence')
    categories = {}
    for channel in channels:
        # 判断组编号是否存在
        if channel.group_id not in categories:
            categories[channel.group_id] = {
                'channels': [],  # 次频道中的一级分类
                'sub_cats': []  # 二季分类
            }
        # 添加一级分类
        categories[channel.group_id]['channels'].append({
            'id': channel.category_id,
            'name': channel.category.name,
            'url': channel.url
        })
        # 添加二季分类
        for sub2 in channel.category.subs.all():
            # 添加三级分类
            sub2.sub_cats = []
            for sub3 in sub2.subs.all():
                sub2.sub_cats.append(sub3)
            categories[channel.group_id]['sub_cats'].append(sub2)

    return categories